import env from "@/config/env";
import Enum from "@/typings/Enum";

/**
 * 文件预览url拼接
 * @param {string} fileName 文件名
 * @param {string} storagePath 文件url地址
 * @return {string}
 *
 */
export function filePreview(fileName: string, storagePath: string): string {
  if (
    fileName.split(".")[1] === "png" ||
    fileName.split(".")[1] === "jpg" ||
    fileName.split(".")[1] === "pdf" ||
    fileName.split(".")[1] === "gif" ||
    fileName.split(".")[1] === "jpeg" ||
    fileName.split(".")[1] === "bmp"
  ) {
    return storagePath;
  } else {
    let userInfo: any = sessionStorage.getItem("userInfo")?.toString();
    userInfo = userInfo ? JSON.parse(userInfo) : {};

    const date = new Date();
    const fullDate = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
    const preString = "上海同济工程咨询有限公司版权所有-" + userInfo.user.nickName;
    const _return = `${env.previewUrl}/view/url?url=${encodeURIComponent(storagePath)}&watermark=${preString}-${fullDate}&name=${encodeURIComponent(fileName)}`;
    return _return;
  }
}

/**
 * 文件显示单位
 * @param {number} len 文件字节长度
 * @return {string} 大于1000000返回单位M，反之返回KB
 */
export function fileSize(len: number): string {
  const x = `${len}`.length > 6 ? 6 : 3;
  return `${(len / Math.pow(10, x)).toFixed(2)}${x === 3 ? "KB" : "M"}`;
}

/**
 * 通过文件名，返回文件icon
 * @param {number} fileName 文件名
 * @return {string} 如：doc,txt...没有获取到后缀名返回空字符串
 */
export function getFileIcon(fileName: string): string {
  const icons: any = Enum.FileType;
  const suffix = fileName.match(/\.([^\\.]+)$/);
  if (suffix && suffix[1] && icons[suffix[1]]) {
    return icons[suffix[1]];
  } else {
    return icons["default"];
  }
}

/**
 * 手机格式验证
 * @param {string} mobile 手机号码
 * @return {boolean}
 */
export function checkPhone(mobile: string) {
  if (!/^1[3456789]\d{9}$/.test(mobile)) {
    return false;
  }
  return true;
}

/**
 * 没有内容显示--
 * @param content
 */
export function showContent(content: string | number) {
  return content || content === 0 ? content : "--";
}
